package com.superb.common.database.p6spy;

import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.FormattedLogger;
import lombok.extern.slf4j.Slf4j;

/**
 * 完整 P6Spy sql日志输出
 * @Author: ajie
 * @CreateTime: 2024-07-03 14:27
 */
@Slf4j
public class P6SpyLogger extends FormattedLogger {

    @Override
    public void logException(Exception e) {
        log.error("P6Spy", e);
    }

    @Override
    public void logText(String text) {
        log.info(text);
    }

    /**
     * 打印sql
     * @param connectionId
     * @param now
     * @param elapsed
     * @param category
     * @param prepared
     * @param sql
     * @param url
     */
    @Override
    public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql, String url) {
        String msg = strategy.formatMessage(connectionId, now, elapsed, category.toString(), prepared, sql, url);
        if (Category.ERROR.equals(category)) {
            log.error(msg);
        } else if (Category.WARN.equals(category)) {
            log.warn(msg);
        } else if (Category.DEBUG.equals(category)) {
            log.debug(msg);
        } else {
            log.info(msg);
        }
    }

    @Override
    public boolean isCategoryEnabled(Category category) {
        if (Category.ERROR.equals(category)) {
            return log.isErrorEnabled();
        } else if (Category.WARN.equals(category)) {
            return log.isWarnEnabled();
        } else {
            return Category.DEBUG.equals(category) ? log.isDebugEnabled() : log.isInfoEnabled();
        }
    }
}
